/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PainelMultiplayer.java
 *
 * Created on 06/12/2011, 20:16:44
 */
package projetointegrado;

import java.awt.Graphics;
import java.awt.Image;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.ScrollPaneConstants;

/**
 *
 * @author Emerson
 */
public class PainelMultiplayer extends javax.swing.JPanel {
//    private int nPlayersOnline;
//    private int nPlayersMaximo;
    private String nome;
   // private BufferedReader reader;
   // private PrintWriter writer;
     ObjectOutputStream os;
    ObjectInputStream ois;
    private Socket sock;
    private String host;
    private int porta;
    public static PainelInferiorMulti pim;
    public static PlayerMulti p = new PlayerMulti();
    public static ArrayList<PlayerMulti> arrayplayer = new ArrayList<PlayerMulti>();
//    private boolean conexaoOk = false;
    public void paintComponent(Graphics g) {
        Image imagem = new ImageIcon("src/Imagens/online.jpg").getImage();
        g.drawImage(imagem, 0, 0, this);
    }
    /** Creates new form PainelMultiplayer */
    public PainelMultiplayer() {
        
        initComponents();
        //fieldEntrada.setAutoscrolls(true);
    
        //fieldEntrada.setLineWrap(true);
        //fieldEntrada.setWrapStyleWord(true);
       // fieldEntrada.setEditable(false);
       // jScrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       // jScrollPane1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        
        jTextField3.setVisible(false);
        jLabel3.setVisible(false);
        jLabel4.setVisible(false);
        jButton2.setVisible(false);
        jLabel5.setVisible(false);
     //   fieldEntrada.setVisible(false);
      //  fieldSaida.setVisible(false);
      //  jButton3.setVisible(false);
    }
    
    public void go(){
        setUpNetworking();
        Thread readerThread = new Thread(new IncomingReader());
        readerThread.start();
    }

    public void setUpNetworking(){
     try{
         sock = new Socket(host, porta);
         //InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
         ois = new ObjectInputStream(sock.getInputStream());
         //reader = new BufferedReader(streamReader);
         //writer = new PrintWriter(sock.getOutputStream());
         os = new ObjectOutputStream(sock.getOutputStream());
         System.out.println("conexao estabelecida");
         jLabel4.setVisible(true);
         jLabel3.setVisible(true);
         jTextField3.setVisible(true);
         jButton2.setVisible(true);
     }catch(Exception ex){ex.printStackTrace();}
    }
    
    public void enviaObjeto(){
        try{
        System.out.println("COMEÇANDO A ENVIAR O OBJETO");
        os.writeObject(p);
        os.flush();
      //  writer.println(nome + ": " + fieldSaida.getText());
      //  writer.flush();
    }catch(Exception ex){ex.printStackTrace();}
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setMinimumSize(new java.awt.Dimension(1024, 710));
        setPreferredSize(new java.awt.Dimension(1024, 710));
        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("host:");
        add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 94, -1, -1));

        jLabel2.setText("porta:");
        add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 124, -1, -1));
        add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 90, 223, -1));
        add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 120, 223, -1));

        jButton1.setText("Conectar");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });
        add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 150, -1, -1));

        jLabel3.setText("Nome do Player:");
        add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 223, -1, -1));
        add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 220, 230, -1));

        jButton2.setText("JOGAR AGORA !");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });
        add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 260, 320, -1));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setForeground(new java.awt.Color(0, 204, 0));
        jLabel4.setText("Conexão OK !!!!!!");
        add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 180, 130, -1));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setForeground(new java.awt.Color(255, 0, 0));
        jLabel5.setText("SERVIDOR CHEIO :(");
        add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(450, 300, -1, -1));
    }// </editor-fold>//GEN-END:initComponents

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
    host = jTextField1.getText();
    porta = Integer.parseInt(jTextField2.getText());
    
    go();
    //if(conexaoOk == false){
//host = jTextField1.getText();
//porta = Integer.parseInt(jTextField2.getText());
//        try {
//            Socket client = new Socket(host, porta);
//            DataInputStream in = new DataInputStream(client.getInputStream());
//            DataOutputStream out = new DataOutputStream(client.getOutputStream());
//            out.writeUTF("conectando");
//            int k = in.readInt(); //recebe a resposa do server verifica se foi bem sucedida...
//            if(k == 666){
//                conexaoOk = true;
//                jTextField3.setVisible(true);
//                jLabel3.setVisible(true);
//                jLabel4.setVisible(true);
//                jButton2.setVisible(true);
//            }
//            nPlayersOnline = in.readInt(); //recebe o numero de players online..
////            System.out.println("players online: " + nPlayersOnline);
//            nPlayersMaximo = in.readInt(); //recebe o numero maximo de players
////            System.out.println("numero maximo de players: " + nPlayersMaximo);
//            
//            
//            //System.out.println(k);
//            in.close();
//            out.close();
//            client.close();
//            
//        } catch (UnknownHostException ex) {
//            Logger.getLogger(PainelMultiplayer.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(PainelMultiplayer.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        
//}
}//GEN-LAST:event_jButton1MouseClicked

private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
    p.nome = jTextField3.getText();
    arrayplayer.add(p);
    //fieldEntrada.setVisible(true);
   // fieldSaida.setVisible(true);
   // jButton3.setVisible(true);
    this.setVisible(false);
    //enviaObjeto();
    pim = new PainelInferiorMulti();
    pim.setBounds(0,550,1024,150);
    ProjetoIntegrado.janelaPrincipal.add(pim);
    pim.setVisible(true);
    JanelaJogoMulti jjm = new JanelaJogoMulti();
    jjm.setBounds(0,0 , jjm.largura, jjm.altura);
    ProjetoIntegrado.janelaPrincipal.add(jjm);
    jjm.setVisible(true);  
    jjm.repaint();
    jjm.requestFocus();
    DesenhaTelaMulti dtm = jjm.criaDesenhaTela();
    
    
//    if(nPlayersOnline < nPlayersMaximo){
//        
//            try {
//                Socket client = new Socket(host, porta);
//                DataInputStream in = new DataInputStream(client.getInputStream());
//                DataOutputStream out = new DataOutputStream(client.getOutputStream());
//                int n = in.readInt();
//                nPlayersOnline = in.readInt();
//                System.out.println("players online: " + nPlayersOnline);
//                nPlayersOnline = in.readInt();
//                System.out.println("numero maximo de players: " + nPlayersMaximo);
//                out.writeUTF(jTextField3.getText()); //envia o nome do player...
//                jTextField3.setText("");
////                in.close();
////                out.close();
////                client.close();
//                //out.writeInt(nPlayersOnline++);
//                
//            } catch (UnknownHostException ex) {
//                Logger.getLogger(PainelMultiplayer.class.getName()).log(Level.SEVERE, null, ex);
//            } catch (IOException ex) {
//                Logger.getLogger(PainelMultiplayer.class.getName()).log(Level.SEVERE, null, ex);
//            }
//            
//    }else{      
//        jLabel5.setVisible(true);
//    }
}//GEN-LAST:event_jButton2MouseClicked


public class IncomingReader implements Runnable{
    public void run(){
        ArrayList<PlayerMulti> pm2 = new ArrayList<PlayerMulti>();
        PlayerMulti p2;
        try{ 
           //ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
            while((p2 = (PlayerMulti) ois.readObject())!= null){
                //p = p2;
                
                for(int i = 0; i < arrayplayer.size(); i++){
                    if(p2.nome.equals(arrayplayer.get(i).nome)){
                        arrayplayer.set(i, p2);
                       // p = p2;
                    }
                    
                }
                if(p2.nome.equals(p.nome)){
                        p = p2;
                    }
                if(!arrayplayer.contains(p2)){
                    arrayplayer.add(p2);
                   // System.out.println("Tamanho da ARRAY: " + arrayplayer.size());
                }
                if(p2.textoImpresso == false){
                    pim.setTextArea(p2.nome + ": " + p2.texto);
                    p2.textoImpresso  = true;
                }
               
               // System.out.println("recebeu um objeto...");
                //oos.writeObject(p);
               // System.out.println(p2.nome);
                //System.out.println(p.y);
              //  System.out.println("read " + message);
               // fieldEntrada.append(message + "\n");
            }
        }catch(Exception ex){ex.printStackTrace();}
    }
}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables
}



